#include <stdio.h>
#include "ohos_init.h"
#include "hi_gpio.h"
#include <unistd.h>
#include "cmsis_os2.h"
#include "lwip/netifapi.h"
#include "hi_wifi_api.h"
#include "hi_types.h"
#include <string.h>
#include "wifiiot_errno.h"
#include "wifiiot_adc.h"
#include "wifiiot_uart.h"
#include "bsp_usart.h"

/* demo3
使用串口1接收串口指令控制绿灯的亮灭
led灯定时闪烁
使用按键KEY ，GPIO外部中断 控制LED灯亮灭 
*/


static void mymain(void);


/* 串口1收发buf */
uint8_t sendBuf[UART_BUFF_SIZE]={0};
uint8_t *sendBuf_ptr = sendBuf;

uint8_t recvBuf[UART_BUFF_SIZE]={0};
uint8_t *recvBuf_ptr = recvBuf;



/* 串口1 任务 */
static void UART_Task(void)
{

    uint32_t ret;
    uint32_t command;


    /* 串口设置 */
    WifiIotUartAttribute uart_attr = 
    {
        .baudRate = 115200,
        .dataBits = 8,
        .stopBits = 1,
        .parity = 0,
    };

    /* 初始化串口 */
    ret = UartInit(WIFI_IOT_UART_IDX_1, &uart_attr, NULL);
    if (ret != WIFI_IOT_SUCCESS)
    {
        printf("Failed to init uart! Err code = %d\n", ret);
        return;
    }

    printf("UART Test Start\n");
    while (1)
    {
        /* 通过串口1接收数据 */
        UartRead(WIFI_IOT_UART_IDX_1, recvBuf_ptr, UART_BUFF_SIZE);

        //usleep(5000);
        /* 串口指令控制LED灯亮灭 */
        command = recvBuf[1];
	    command = (command <<8)  +  recvBuf[2];

        switch(command)
        {
            case LEDON:
                GreenLedOn();

                sendBuf[0] = 0x11;
                Usart_SendArray(sendBuf,10);
                break;
            
            case LEDOFF:
                GreenLedOff();
                break;

            default:
                break;

        }        
    }
}


/* 创建串口工作任务 */
static void UART_ExampleEntry(void)
{

    osThreadAttr_t attr;
    attr.name = "UART_Task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = UART_TASK_STACK_SIZE;
    attr.priority = UART_TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)UART_Task, NULL, &attr) == NULL)
    {
        printf("[ADCExample] Falied to create UART_Task!\n");
    }
}

static void LedTask(void)
{

    while (1)
    {
        WhiteLedOn();
        osDelay(50);
        WhiteLedOff();
        osDelay(50);
    }
}


/*entry  加入，登记 */
static void LedEntry(void)
{

    osThreadAttr_t attr;
    attr.name = "LedTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 4096;
    attr.priority = osPriorityNormal;

    if (osThreadNew((osThreadFunc_t)LedTask, NULL, &attr) == NULL)
    {
        printf("[LedEntry] Falied to create LedTask!\n");
    }
}


/* 主函数 */
static void mymain(void)
{

    printf("=======================================\r\n");
    printf("****************LED_KEY****************\r\n");
    printf("=======================================\r\n");


    LED_INIT();
    GreenLedOff();
    KEY_INIT();
    UART_ExampleEntry();
    LedEntry();
}






APP_FEATURE_INIT(mymain);
